package leetcode.others;

import java.util.ArrayList;
import java.util.Random;

//7. 整数反转

/**
 * 注意事项：1.int类型  -2147483648到2147483647
 * System.out.println((int)Long.parseLong("-2147483648"));还是-2147483648
 * Math.abs(-2147483648) 还是 -2147483648  因为正数比他小一个
 */
public class Reverse {
    public static void main(String[] args) {
//        System.out.println(reverse2(-2147488));
//        System.out.println((int)Long.parseLong("-2147483648"));
//        StringBuilder stringBuilder = new StringBuilder("aaa");
//        stringBuilder.insert(0,"-");
//        stringBuilder.append("bbb");
//        System.out.println(stringBuilder.toString());
        System.out.println(isPalindrome(123));

    }

    public static int reverse(int x) {

        if (x % 10 == x) {
            return x;
        }
        if (x == -2147483648) {
            return 0;
        }
        int maxLength = 0;
        String s = x + "";
        if (x < 0) {
            maxLength = s.substring(1, s.length()).length();
        } else {
            maxLength = (x + "").length();
        }


        ArrayList<String> list = new ArrayList<>();
        for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
            System.out.println(Math.abs(x));
            list.add(Math.abs(x) / n % 10 + "");
        }
        StringBuffer stringBuilder1 = new StringBuffer();
        for (String item : list) {
            stringBuilder1.append(item);
        }
        if (x < 0) {
            stringBuilder1.insert(0, "-");
        }
        return (int) Long.parseLong(stringBuilder1.toString()) == Long.parseLong(stringBuilder1.toString()) ? (int) Long.parseLong(stringBuilder1.toString()) : 0;

    }

    public static int reverse2(int x) {
        long rev = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;
            rev = rev * 10 + digit;
        }
        return (int) rev == rev ? (int) rev : 0;
    }

    //回文
    public static boolean isPalindrome(int x) {

        if (x < 0) {
            return false;
        }
        long res = 0;
        while (x != 0) {

            int digit = x % 10;
            x /= 10;
            res = res * 10 + digit;
        }
        return res == x;
    }

    //回文，，利用jdk
    public static boolean isPalindrome2(int x) {
        StringBuilder stringBuilder = new StringBuilder(x+"");
        String res = stringBuilder.reverse().toString();
        return (x+"").equals(res);

    }

}
